/**
 * 
 */
package com.qyxx.platform.sysmng.notice.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;


import com.google.common.collect.Lists;
import com.qyxx.platform.common.orm.PropertyFilter;
import com.qyxx.platform.common.utils.web.struts2.Struts2Utils;
import com.qyxx.platform.sysmng.accountmng.dao.OrganizationDao;
import com.qyxx.platform.sysmng.accountmng.dao.RoleDao;
import com.qyxx.platform.sysmng.accountmng.entity.Authority;
import com.qyxx.platform.sysmng.accountmng.entity.AuthorityJson;
import com.qyxx.platform.sysmng.accountmng.entity.Organization;
import com.qyxx.platform.sysmng.accountmng.entity.Role;
import com.qyxx.platform.sysmng.accountmng.entity.RoleJson;
import com.qyxx.platform.sysmng.notice.dao.CommonTypeDao;
import com.qyxx.platform.sysmng.notice.entity.CommonType;
import com.qyxx.platform.sysmng.utils.Constants;

/**
 * @author yulq
 *
 */

@Component
@Transactional
public class CommonTypeManager {
	private static final String FIND_TYPELIST="select a from CommonType a where a.typeVal = ?";
	private static final String FIND_TYPELIST_BY_NAME="select a from CommonType a where a.name = ? and a.typeVal = ?";
	private static final String FIND_TYPE_COUNT = "select a from CommonType a where a.typeVal = ? and a.pid is null";
	/**
	 * 根据用户查询系统分类
	 */
	private static final String FIND_SYSTEM_TYPE_BY_USER = "select distinct a from CommonType a inner join a.roleList b where a.typeVal = ? and a.status = ? and a.typeBelong = ?" +
			" and b.id in (select e.id from User d inner join d.roleList e where d.id = ?) order by a.pid asc, a.sortOrderNo asc";
	
	//查询通用分类
	private static final String FIND_COMMON_TYPE = "select a from CommonType a where a.typeVal = ? order by a.pid asc, a.sortOrderNo asc";
	
	//查询系统分类
	private static final String FIND_SYSTEM_TYPE_ALL = "select a from CommonType a where a.typeBelong = ? order by a.pid asc, a.sortOrderNo asc";
	
	//设置排序号
	private static final String UPDATE_TYPE_SORT_ORDER_NO = "update CommonType a set a.sortOrderNo = ? where a.id = ?";
	
	//排序号位数，3位支持1000个分类
	private static final Integer BIT_NUM = 3;
	
	private CommonTypeDao commonTypeDao;
	private RoleDao roleDao;
	private OrganizationDao organizationDao;
	
	public CommonTypeDao getCommonTypeDao() {
		return commonTypeDao;
	}
	@Autowired
	public void setOrganizationDao(OrganizationDao organizationDao) {
		this.organizationDao = organizationDao;
	}
	@Autowired
	public void setRoleDao(RoleDao roleDao) {
		this.roleDao = roleDao;
	}
    @Autowired
	public void setCommonTypeDao(CommonTypeDao commonTypeDao) {
		this.commonTypeDao = commonTypeDao;
	}


    /**
     * 查找类别是通知的
     * @return
     */
    public List<CommonType> findNoticeType(){
    	return commonTypeDao.find(FIND_TYPELIST, CommonType.TYPE_NOTICE);
    }
	
    /**
     * 查找类别是新闻的
     * @return
     */
    public List<CommonType> findNewsType(){
    	return commonTypeDao.find(FIND_TYPELIST, CommonType.TYPE_NEWS);
    }

    /**
     * 根据类型名称查询通知类别
     * 
     * @param name
     * @return
     */
    public List<CommonType> findNoticeTypeByName(String name){
    	return findTypeByName(name, CommonType.TYPE_NOTICE);
    }
    
    /**
     * 根据类型名称查询新闻类别
     * 
     * @param name
     * @return
     */
    public List<CommonType> findNewsTypeByName(String name){
    	return findTypeByName(name, CommonType.TYPE_NEWS);
    }
 
    /**
     * 根据类型查数据里有没有该记录
     * @param name
     * @return
     */
    public List<CommonType> findTypeByName(String name, String type){
    	List<CommonType> list=commonTypeDao.find(FIND_TYPELIST_BY_NAME, name, type);
    	return list;
    }
    
    /**
     * 新增通知类型之前判断数据库里是否有该记录
     * @param name
     * @param userId
     * @return
     */
    public CommonType addNoticeType(String name,Long userId,Long pid){
    	CommonType commonType=new CommonType();
    	commonType.setPid(pid);
    	commonType.setName(name);
    	commonType.setCreateTime(new Date());
    	commonType.setCreateUser(userId);
    	commonType.setTypeVal(CommonType.TYPE_NOTICE);
    	commonTypeDao.save(commonType);
    	return commonType;
    	
    }
    
    /**
     * 删除公用类型
     * @param id
     */
    public void deleteCommonType(Long[] ids){
    	for(Long id:ids){
    		commonTypeDao.delete(id);
    	}
    	
    }
    
    
    /**
     * 新增通知类型之前判断数据库里是否有该记录
     * @param name
     * @param userId
     * @return
     */
    public CommonType addNewsType(String name,Long userId,Long pid){
    	CommonType commonType=new CommonType();
    	commonType.setPid(pid);
    	commonType.setName(name);
    	commonType.setCreateTime(new Date());
    	commonType.setCreateUser(userId);
    	commonType.setTypeVal(CommonType.TYPE_NEWS);
    	commonTypeDao.save(commonType);
    	return commonType;
    	
    }
    
    /**
     * 保存通用类型
     * 
     * @param ct
     * @param userId
     */
    public void saveCommonType(CommonType ct, Long userId) {
    	if(null!=ct.getId()) {
    		ct.setLastUpdateTime(new Date());
    		ct.setLastUpdateUser(userId);
    	} else {
    		ct.setCreateTime(new Date());
        	ct.setCreateUser(userId);
    	}
    	commonTypeDao.save(ct);
    	resetTypeSortOrderNo(ct);
    }
    
    /**
     * 根据idSort更新顺序号
     * 
     * @param ct
     */
    public void resetTypeSortOrderNo(CommonType ct) {
    	String sn = ct.getIdSort();
    	String[] sa = StringUtils.split(sn, ",");
    	int i = 1;
    	for(String s : sa) {
    		commonTypeDao.batchExecute(UPDATE_TYPE_SORT_ORDER_NO, StringUtils.leftPad(String.valueOf(i++), BIT_NUM, "0"), Long.valueOf(s));
    	}
    }
    
    /**
     * 获取通用类别方法
     * 
     * @param type
     * @return
     */
    public List<CommonType> findCommonType(String type){
    	//return commonTypeDao.findBy("typeVal", type);
    	return commonTypeDao.find(FIND_COMMON_TYPE, type);
    }
    
    /**
     * 根据用户及类别Key获取系统类别数据
     * 
     * @param type
     * @param userId
     * @return
     */
    public List<CommonType> findSysCommonType(String type, Long userId){
    	return commonTypeDao.find(FIND_SYSTEM_TYPE_BY_USER, type, Constants.IS_USING, CommonType.TYPE_SYSTEM, userId);
    }
    
    /**
     * 根据ID获取对象
     * 
     * @param id
     * @return
     */
    public CommonType get(Long id) {
    	return commonTypeDao.get(id);
    }
    /**
     * 获取所有系统类型
     * 
     */
    public List<CommonType> getAllSystemType(){
    	/*List<CommonType> list = new ArrayList<CommonType>();
    	List<PropertyFilter> filters = new ArrayList<PropertyFilter>();
		PropertyFilter belongFilter = new PropertyFilter(
				"EQS_typeBelong", CommonType.TYPE_SYSTEM);
		filters.add(belongFilter);
		list = commonTypeDao.find(filters);
		return list;*/
    	return commonTypeDao.find(FIND_SYSTEM_TYPE_ALL, CommonType.TYPE_SYSTEM);
    }
    /**
     * 获取当前系统类型关联的角色集合
     * 
     */
    public List<RoleJson> getRoleList(Long tid){
    	List<RoleJson> list = new ArrayList<RoleJson>();
    
		List<Organization> orgList = organizationDao.getAll();
		for (int i = 0; i < orgList.size(); i++) {
			Organization org1 = orgList.get(i);
			Long orgId = orgList.get(i).getId();
			String name = orgList.get(i).getOrganizationName();
			RoleJson rj = new RoleJson(orgId, name, org1);
			rj.setNocheck(false);
			list.add(rj);
		}
		List<Role> selRoleList  =new ArrayList<Role>();
		if (tid!=null){
			CommonType ct = commonTypeDao.get(tid);
	    	selRoleList  = ct.getRoleList();
    	}
	    	
	    	List<PropertyFilter> filters = new ArrayList<PropertyFilter>();
			PropertyFilter roleStatusFilter = new PropertyFilter(
					"EQS_roleStatus", Constants.IS_USING);
			filters.add(roleStatusFilter);
			List<Role> roleList = roleDao.find(filters);

			for (int j = 0; j < roleList.size(); j++) {
				Long org_id = roleList.get(j).getOrganization().getId();
				Long roleid = roleList.get(j).getId();
				String rolename = roleList.get(j).getRoleName();
				RoleJson rjk = new RoleJson(roleid, rolename, org_id);
				if(selRoleList.size()>0){
					for (int k = 0; k < selRoleList.size(); k++) {
						if (selRoleList.get(k).getId() == roleid) {
							rjk.setChecked(true);
						}
					}
				}
				list.add(rjk);
			}
		
		return list;
    }
    /**
     * 保存系统类型
     * 
     * @param ct
     * @param rIds
     * @param userId
     */
    public void saveSystemType(CommonType ct, String rIds,Long userId) {
    	Long cId = ct.getId();
    	if(null!=cId) {//修改
    		ct.setLastUpdateTime(new Date());
    		ct.setLastUpdateUser(userId);
        	commonTypeDao.deleteCommonTypeId(cId);//先删除关联表中桌面和角色的记录
    	} else {//新增
    		ct.setTypeBelong(CommonType.TYPE_SYSTEM);
    		ct.setCreateTime(new Date());
        	ct.setCreateUser(userId);
    	}
    	commonTypeDao.save(ct);
    	//commonTypeDao.flush();
    	cId = ct.getId();
		if (StringUtils.isNotBlank(rIds)){//再添加记录
               String roleIds[] = rIds.split(",");
			for (String roleId : roleIds) {
				Long rId = Long.valueOf(roleId);
				commonTypeDao.saveCommonTypes(cId, rId);
			}
		} 
    }

	/**
	 * 删除系统类型
	 * 
	 * @param id
	 */
	public void deleteSystemType(Long id) {
		CommonType commonType = this.get(id);
		commonType.setStatus(Constants.NO_USING);	
	}
	/**
	 * 校验系统类型的typeVal
	 */
	public Boolean validateVal(String typeVal,Long id) {
		String hql = FIND_TYPE_COUNT;
		List<Object> list = Lists.newArrayList();
		list.add(typeVal);
		if(id!=null){//修改
			hql += " and a.id <> ?";
			list.add(id);
		}
		return commonTypeDao.find(hql, list.toArray()).size() == 0;
	}
	/**
	 * 根据用户ID和角色ID来查找相应权限列表
	 */
	public List<CommonType> getTypeList(Long roleId) {
		List<PropertyFilter> filters = new ArrayList<PropertyFilter>();
		PropertyFilter belongFilter = new PropertyFilter(
				"EQS_typeBelong", CommonType.TYPE_SYSTEM);
		filters.add(belongFilter);
		PropertyFilter statusFilter = new PropertyFilter(
				"EQS_status", Constants.IS_USING);
		filters.add(statusFilter);	
		List<CommonType> list = commonTypeDao.find(filters);

		if (roleId != null) {
			Role role = roleDao.get(roleId);
			List<CommonType> selectList = role.getCommonTypeList();
			Long b = 0L;
			for (int i = 0; i < selectList.size(); i++) {
				b = selectList.get(i).getId();
				for (int j = 0; j < list.size(); j++) {
					if (b == list.get(j).getId()) {
						list.get(j).setChecked(true);
					}
				}
			}
			return list;
		}
		return list;
	}
	
	
	/**
	 * 根据id列表查询分类
	 * 
	 * @param ids
	 * @return
	 */
	public List<CommonType> getTypeListByIds(String ids) {
		List<PropertyFilter> filters = new ArrayList<PropertyFilter>();
		PropertyFilter filter = new PropertyFilter(
				"INL_id", ids);
		filters.add(filter);
		return commonTypeDao.find(filters);
	}
}
